/*
  学习目标：数据缓存
  步骤：
     1. 
     2. 
     3. 
*/
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { checkAllAction, delByIdAction, updateByIdAction } from '../store/action';

export function Main() {
  const { list, type } = useSelector((state) => state);
  const dispatch = useDispatch();

  const isAll = list.length ? list.every((item) => item.isDone) : false;

  const showList = list.filter((item) => {
    if (type === 'all') return true;
    if (type === 'active') return !item.isDone;
    return item.isDone;
  });

  // 1. 监听lise的变化, 实时 存缓存中
  useEffect(() => {
    localStorage.setItem('redux-todo-list', JSON.stringify(list));
  }, [list]);

  return (
    <section className="main">
      <input
        checked={isAll}
        onChange={(e) => dispatch(checkAllAction(e.target.checked))}
        id="toggle-all"
        className="toggle-all"
        type="checkbox"
      />
      <label htmlFor="toggle-all">全选</label>
      <ul className="todo-list">
        {showList.map((item) => {
          return (
            <li key={item.id} className={item.isDone ? 'completed' : ''}>
              <div className="view">
                <input
                  onChange={() => dispatch(updateByIdAction(item.id))}
                  checked={item.isDone}
                  className="toggle"
                  type="checkbox"
                />
                <label>{item.task}</label>
                <button
                  onClick={() => dispatch(delByIdAction(item.id))}
                  className="destroy"
                ></button>
              </div>
            </li>
          );
        })}
      </ul>
    </section>
  );
}
